package lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 *  读和写都要加锁
 *  (之前有一个疑问,为什么读也要锁,后面通过测试发现, 读如果不加锁,
 *  可能别人没写完你就读了,这样就没读到,所以读写都要加锁)
 *
 * @author jiangwz
 * @create 2019/9/14.
 */
public class ReadWriteLockDemo {

    ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    static volatile Map<Integer, Object> map = new HashMap<>();

    public void put(Integer key, Object val){
        rwLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 正在写");
            try {
                //这里模拟网络耗时
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            map.put(key,val);
            System.out.println(Thread.currentThread().getName() + " 写完了");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rwLock.writeLock().unlock();
        }

    }

    public void get(Integer key) {
        rwLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正在读");
            try {
                // 很奇怪,一定要先睡才能出现错误
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Object res = map.get(key);
            System.out.println(Thread.currentThread().getName() + "正在读 result=" + res);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rwLock.readLock().unlock();
        }

    }

    public static void main(String[] args){
        int threadNum = 5;
        ReadWriteLockDemo writeLockDemo = new ReadWriteLockDemo();
        for (int i = 0; i < threadNum; i++) {
            final int num = i;
            new Thread(() -> {
                writeLockDemo.put(num, num);
            }, "write" + i).start();
        }

        for (int i = 0; i < threadNum; i++) {
            final int num = i;
            new Thread(() -> {
                writeLockDemo.get(num);
            }, "read " + i).start();
        }
    }
}
